package indi.kider.server.woniubus.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.DevLock;
import indi.kider.common.model.apartment.DevLockCard;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.util.HttpClientUtils;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apartment.mapper.DevLockCardMapper;
import indi.kider.server.apartment.mapper.DevLockMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.employee.mapper.TenantMapper;
import indi.kider.server.woniubus.model.DevLockCardVo;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vankid.common.model.base.CommonResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@SuppressWarnings("ALL")
@Log
public class CardServiceImpl implements CardService {


    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private DevLockMapper devLockMapper;
    @Autowired
    private DevLockCardMapper devLockCardMapper;

    @Value("${iot.url}")
    private String ioturl;
    @Value("${iot.sourceId}")
    private String sourceId;
    @Override
    @Transactional(rollbackFor=Exception.class)
    public CommonResponse addCard(DevLockCardVo devLockCardVo) throws Exception {
        if(Strings.isNullOrEmpty(devLockCardVo.getCard())){
            throw new Exception("卡编号不能为空！");
        }
        if(devLockCardVo.getCard().length()>10){
            throw new Exception("卡编号不能超过10！");
        }
        Long rentId = devLockCardVo.getRentId();
        Rent rent = rentMapper.selectByPrimaryKey(rentId);
        if(rent.getState() != 1){
            throw new Exception("只有租住的用户才能发卡！");
        }
        Long housesId = rent.getHousesId();
        DevLock devLock = new DevLock();
        devLock.setHouseId(housesId);
        devLock.setState(2);//1:未安装;2:已绑定用户 99失效
        DevLock lock = null;
        try{
            lock = devLockMapper.selectOne(devLock);
        }catch (Exception e){
            throw new Exception("房间存在多个锁具信息,请后台维护人员检查!");
        }
        if(lock==null){
            throw new Exception("锁具不存在,请检查!");
        }
        DevLockCard devLockCard = devLockCardVo;
        devLockCard.setLockId(lock.getId().toString());
        devLockCard.setTenantId(rent.getTenantId());
//        判断租客卡片数量是否超过设置数量===============start
        Tenant tenant =  tenantMapper.selectByPrimaryKey(devLockCard.getTenantId());
        int cardCnt = tenant.getCardCnt();
        DevLockCard dc = new DevLockCard();
        dc.setTenantId(tenant.getId());
        dc.setLockId(devLockCard.getLockId());
        dc.setState(1);//有效
        //用户有效卡片数量
        int cnt= devLockCardMapper.selectCount(dc);
        if(cardCnt<=cnt){
            throw new Exception("用户【"+tenant.getName()+"】,已存在"+cnt+"张卡片,不能再新增卡片!");
        }
//        判断租客卡片数量是否超过设置数量=================end
        devLockCard.setAddTime(new Date());
        devLockCard.setOpenCardTime(new Date());
        devLockCard.setState(1);
        devLockCard.setOpenCardRemark(Strings.isNullOrEmpty(devLockCard.getOpenCardRemark())?"PC端管理员开卡":devLockCard.getOpenCardRemark());
        Integer result = devLockCardMapper.insertSelective(devLockCard);

        //调用NB接口
        try{
            Map<String, String> params = new HashMap<String,String>();
            params.put("imei",devLock.getImei());
            params.put("userId",tenant.getId()+"");
            params.put("icCard",devLockCard.getCard());
            params.put("sourceId",sourceId);
            String  str = HttpClientUtils.postForm(ioturl+"iccard/add", params, null, 10000, 10000);
            JSONObject obj = JSON.parseObject(str);
            Integer status = obj.getInteger("status");
            if(status!=1){
                throw new Exception("IOT返回状态【"+status+"】错误!");
            }
        }catch (Exception e){
            throw new Exception("访问IOT接口出错:"+e.getMessage());
        }
        return CommonResponse.buildBadRequestResponse("新增卡片成功",null);
    }

    /**
     *
     * 删除卡片
     * @param devLockCardVo
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public CommonResponse delCard(DevLockCardVo devLockCardVo) throws Exception {
        DevLockCard devLockCard = devLockCardVo;
        devLockCard.setState(0);
        if(devLockCard.getClearCardRemark() == null){
            devLockCard.setClearCardRemark("PC端管理员销卡");
        }else{
            devLockCard.setClearCardRemark(devLockCard.getClearCardRemark());
        }
        devLockCard.setClearCardTime(new Date());
        int result =  devLockCardMapper.updateByPrimaryKeySelective(devLockCard);
        //=================================>
        Long rentId = devLockCardVo.getRentId();
        Rent rent = rentMapper.selectByPrimaryKey(rentId);
        Long housesId = rent.getHousesId();
        DevLock devLock = new DevLock();
        devLock.setHouseId(housesId);
        devLock.setState(2);//1:未安装;2:已绑定用户 99失效
        DevLock lock = null;
        try{
            lock = devLockMapper.selectOne(devLock);
        }catch (Exception e){
            throw new Exception("房间存在多个锁具信息,请后台维护人员检查!");
        }
        if(lock==null){
            throw new Exception("锁具不存在,请检查!");
        }
        //调用NB接口
        try{
            Map<String, String> params = new HashMap<String,String>();
            params.put("imei",devLock.getImei());
            params.put("userId",rent.getTenantId()+"");
            params.put("icCard",devLockCard.getCard());
            params.put("sourceId",sourceId);
            String  str = HttpClientUtils.postForm(ioturl+"iccard/delete", params, null, 10000, 10000);
            JSONObject obj = JSON.parseObject(str);
            Integer status = obj.getInteger("status");
            if(status!=1){
                throw new Exception("IOT返回状态【"+status+"】错误!");
            }
        }catch (Exception e){
            throw new Exception("访问IOT接口出错:"+e.getMessage());
        }
        return CommonResponse.buildBadRequestResponse("注销卡片成功",null);
    }

    public CommonResponse queryCard(DevLockCardVo devLockCardVo) throws Exception {
        List<DevLockCard> list = devLockCardMapper.select(devLockCardVo);
        return CommonResponse.buildDefaultSuccessResponse("查询成功",list);
    }

}
